package lock;

import java.util.concurrent.atomic.AtomicReference;

/**
 自定义自旋锁
 */
public class Spinlock {

    //Thread null
    //原子引用
    volatile AtomicReference<Thread> atomicReference = new AtomicReference<>();

    //加锁
    public void lock(){
        //获取当前线程
        Thread thread = Thread.currentThread();
        //提示当前线程
        System.out.println(Thread.currentThread().getName() + " ==>  lock !");

        //自旋锁
        //若泛型为空，则当前线程自旋，CAS实现
        while(!atomicReference.compareAndSet(null,thread)){

        }
    }


    //解锁
    public void unlock(){
        //获取当前线程
        Thread thread = Thread.currentThread();
        //提示解锁
        System.out.println(Thread.currentThread().getName() + " ==>  unlock ~");
        atomicReference.compareAndSet(thread,null);
    }

}
